package com.day12_Thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: SellTicket
 * @Author: zw
 * @Description: 出百万拳，行万里路；
 * @Create 2024/3/23-21:28
 * @Version 1.0
 */
public class SellTicket implements Runnable {
    private int tickets = 100;
    private Object obj = new Object();

    // ReenTrantLock 方法
    private Lock lock = new ReentrantLock();
    @Override
    public void run() {
        // 这里obj 必须是要同一个对象。 必须要是同一把锁
//        synchronized (obj) {
//            while (tickets > 0) {
//                // 卖票出票也是需要时间
//                // 通过sleep让当前窗口进行出票，
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//                tickets--;
//                System.out.println(Thread.currentThread().getName() + ":" + this.tickets);
//            }
//        }


        lock.lock(); //  加锁
        while (tickets > 0) {
            // 卖票出票也是需要时间
            // 通过sleep让当前窗口进行出票，
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            tickets--;
            System.out.println(Thread.currentThread().getName() + ":" + this.tickets);
        }
        lock.unlock(); //释放锁
    }
}
